package com.biwano.swapmyjob.dao;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.biwano.swapmyjob.mail.AccountCreatedMailSender;
import com.biwano.swapmyjob.mail.MailConnectionManager;
import com.biwano.swapmyjob.objects.User;


@Stateless
public class UserDao extends BaseDao<User>{


	@EJB
	LinkDao linkDao;
	
	@EJB
	MailConnectionManager mailConnectionManager;

	@PersistenceContext
	EntityManager em;


	public boolean emailExists(String email) {
		return entityExists("email", email);
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void register(User user) {

		em.persist(user);

		String linkId = linkDao.createLink(user.getLogin(),
				LinkDao.LinkType.validateEmail);

		AccountCreatedMailSender.sendMail(mailConnectionManager,
				user.getEmail(), user.getLogin(), linkId);

	}

	public User authentify(String login, String password) throws DBException {
		User u = findEntity(login);
		if (u != null && u.getPassword().equals(password)) {
			return u;
		}
		else
			throw new DBException();
	}

	@Override
	public EntityManager getEntityManager() {
		return em;
	}

	@Override
	public Class<User> getClazz() {
		return User.class;
	}

}
